<?php
/**
 * 数据库导入脚本
 * 用于将备份的数据导入到本地数据库
 */

// 本地数据库配置
$localConfig = [
    'hostname' => 'localhost',
    'database' => 'oa5',
    'username' => 'root',
    'password' => '123456',
    'hostport' => '3306',
    'charset'  => 'utf8mb4',
];

// 查找最新的备份文件
$backupFiles = glob("oa_backup_*.sql");
if (empty($backupFiles)) {
    die("错误: 没有找到备份文件\n");
}

// 按修改时间排序，获取最新的备份文件
usort($backupFiles, function($a, $b) {
    return filemtime($b) - filemtime($a);
});

$backupFile = $backupFiles[0];
echo "使用备份文件: $backupFile\n";

try {
    echo "连接到本地数据库...\n";
    
    // 创建数据库连接
    $dsn = "mysql:host={$localConfig['hostname']};port={$localConfig['hostport']};charset={$localConfig['charset']}";
    $pdo = new PDO($dsn, $localConfig['username'], $localConfig['password'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
    
    // 创建数据库（如果不存在）
    $pdo->exec("CREATE DATABASE IF NOT EXISTS `{$localConfig['database']}` CHARACTER SET {$localConfig['charset']} COLLATE utf8mb4_unicode_ci");
    echo "数据库 '{$localConfig['database']}' 已创建或已存在\n";
    
    // 重新连接到指定数据库
    $dsn = "mysql:host={$localConfig['hostname']};port={$localConfig['hostport']};dbname={$localConfig['database']};charset={$localConfig['charset']}";
    $pdo = new PDO($dsn, $localConfig['username'], $localConfig['password'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
    
    echo "开始导入数据...\n";
    
    // 读取备份文件
    $sqlContent = file_get_contents($backupFile);
    
    // 分割SQL语句
    $sqlStatements = explode(";\n", $sqlContent);
    
    $totalStatements = count($sqlStatements);
    $executedStatements = 0;
    $errors = 0;
    
    echo "总共需要执行 $totalStatements 条SQL语句\n";
    
    // 执行每条SQL语句
    foreach ($sqlStatements as $sql) {
        $sql = trim($sql);
        if (empty($sql)) {
            continue;
        }
        
        try {
            $pdo->exec($sql);
            $executedStatements++;
            
            // 显示进度
            if ($executedStatements % 1000 == 0) {
                echo "已执行 $executedStatements/$totalStatements 条语句\r";
            }
        } catch (PDOException $e) {
            $errors++;
            // 忽略一些非关键错误
            if (strpos($e->getMessage(), 'database exists') === false && 
                strpos($e->getMessage(), 'table exists') === false) {
                echo "执行SQL时出错 (语句 $executedStatements): " . $e->getMessage() . "\n";
                echo "SQL: " . substr($sql, 0, 100) . "...\n";
            }
        }
    }
    
    echo "\n导入完成！\n";
    echo "成功执行: $executedStatements 条语句\n";
    echo "错误数量: $errors\n";
    echo "数据库 '{$localConfig['database']}' 导入完成\n";
    
} catch (PDOException $e) {
    echo "数据库连接错误: " . $e->getMessage() . "\n";
} catch (Exception $e) {
    echo "导入过程中发生错误: " . $e->getMessage() . "\n";
}